<?php

namespace Admin\Controller;

use Common\Controller\BaseController;

/**
 * 苗木管理
 */
class TreeController extends BaseController {

    /**
     * 苗木列表
     */
    public function treeList() {
        set_time_limit(0);
        $pageSize = I('post.pageSize', C('PAGE_SIZE'));
        $pageCurrent = I('post.pageCurrent', 1);
        $orderField = I('post.orderField', 't.id');
        $orderDirection = I('post.orderDirection', 'DESC');

        $base_id = I('post.base_id', 0);
        $block_id = I('post.block_id', 0);
        $large_type = I('post.large_type', 0);
        $small_type = I('post.small_type', 0);
        $attr = I('post.attr', array());

        //参数数组
        $params = array();
        //连表条件
        $join = '';
        //构造WHERE条件
        $where = '1=1 ';
        if (!empty($base_id)) {
            $params['base_id'] = $base_id;
            $where .= "AND ba.id={$base_id} ";
        }
        if (!empty($block_id)) {
            $params['block_id'] = $block_id;
            $where .= "AND bl.id={$block_id} ";
        }
        if (!empty($large_type)) {
            $params['large_type'] = $large_type;
            $where .= "AND tt2.id={$large_type} ";
        }
        if (!empty($small_type)) {
            $params['small_type'] = $small_type;
            $where .= "AND tt.id={$small_type} ";
        }
        
        if (!empty($attr)) {
            $treeAttrTable = C('DB_PREFIX') . 'tree_attr';

            foreach ($attr as $ak => $item) {
                if (!empty($item)) {
                    $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak} ON ta{$ak}.tree_id=t.id ";
                    
                    if (is_array($item)) {
                        if (array_key_exists('start', $item) && array_key_exists('end', $item)) {
                            if (!empty($item['start']) && !empty($item['end'])) {
                                $where .= "AND (ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value>={$item['start']} AND ta{$ak}.attr_value<={$item['end']}) ";
                            }
                        } else {
                            foreach ($item as $ik => $val) {
                                $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak}{$ik} ON ta{$ak}{$ik}.tree_id=t.id ";
                                $where .= "AND (ta{$ak}{$ik}.attr_id={$ak} AND ta{$ak}{$ik}.attr_value='{$val}') ";
                            }
                        }
                    } else {
                        $where .= "AND (ta{$ak}.tree_id=t.id AND ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value='{$item}') ";
                    }
                }
            }
        }

        $tree = M('Tree');
        //数据总数
        $total = $tree->alias('t')
                ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->join($join)
                ->where($where)
                ->count('DISTINCT t.id');

        //数据列表
        $list = $tree->distinct(true)
                ->field('t.*,tt2.name AS large_name,tt.name AS small_name,bl.sn AS block_sn')
                ->alias('t')
                ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->join($join)
                ->where($where)
                ->order("{$orderField} {$orderDirection}")
                ->page("{$pageCurrent},{$pageSize}")
                ->select();

        if (!empty($list)) {
            $treeStatus = C('TREE_STATUS');
            $isSign = C('IS_SIGN');
            foreach ($list as &$item) {
                $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', intval($item['add_time'])) : '';
                $item['status'] = array_key_exists($item['status'], $treeStatus) ? $treeStatus[$item['status']] : '';
                $item['is_sign'] = array_key_exists($item['is_sign'], $isSign) ? $isSign[$item['is_sign']] : '';

                $attrList = M('TreeAttr')->field('a.name,a.unit,a.attr_type,ta.attr_value')
                        ->alias('ta')
                        ->join('LEFT JOIN __ATTR__ AS a ON a.id=ta.attr_id')
                        ->where("ta.tree_id={$item['id']}")
                        ->select();

                if (!empty($attrList)) {
                    foreach ($attrList as $attrItem) {
                        //自有属性类型为文本的带单位
                        if ($attrItem['attr_type'] == 1) {
                            $item['attr'] .= "{$attrItem['name']} : {$attrItem['attr_value']} {$attrItem['unit']} <br />";
                        } else {
                            $item['attr'] .= "{$attrItem['name']} : {$attrItem['attr_value']} <br />";
                        }
                    }
                }
            }
            unset($item);
        }

        //获取基地信息
        $base = M('Base')->field('id,name')->where('status=1')->select();

        //获取地块信息
        $block = array();
        if (!empty($base_id)) {
            $block = M('Block')->field('id,sn')->where("status=1 AND base_id={$base_id}")->select();
        }

        //获取苗木分类
        $largeType = M('TreeType')->field('id,name')->where("status=1 AND pid=0")->select();

        //获取苗木种类
        $smallType = array();
        if (!empty($large_type)) {
            $smallType = M('TreeType')->field('id,name')->where("status=1 AND pid={$large_type}")->select();
        }

        //获取苗木自有属性
        if (!empty($small_type)) {
            $treeAttr = $this->getTreeAttr($small_type, $attr, true);
        }

        $this->assign('pageSize', $pageSize);
        $this->assign('pageCurrent', $pageCurrent);
        $this->assign('orderField', $orderField);
        $this->assign('orderDirection', $orderDirection);
        $this->assign('total', $total);
        $this->assign('list', $list);
        $this->assign('params', $params);
        $this->assign('base', $base);
        $this->assign('block', $block);
        $this->assign('largeType', $largeType);
        $this->assign('smallType', $smallType);
        $this->assign('treeAttr', $treeAttr);
        $this->display();
    }

    /**
     * 添加单棵苗木
     */
    public function addOneTree() {
        if (IS_POST) {
            $base_id = I('post.base_id', 0);
            $block_id = I('post.block_id', 0);
            $large_type = I('post.large_type', 0);
            $small_type = I('post.small_type', 0);
            $attr = I('post.attr', array());
            $status = I('post.status', 0);
            $row = I('post.row', 0);
            $col = I('post.col', 0);
            $tree = M('Tree');

            if (empty($base_id)) {
                ajaxReturn('请选择所属基地', 300);
            }
            if (empty($block_id)) {
                ajaxReturn('请选择所属地块', 300);
            }
            if (empty($large_type)) {
                ajaxReturn('请选择苗木分类', 300);
            }
            if (empty($small_type)) {
                ajaxReturn('请选择苗木种类', 300);
            }

            //if (!empty($attr)) {
            //    foreach ($attr as $val) {
            //        if (empty($val)) {
            //            ajaxReturn('请设置苗木自有属性', 300);
            //        }
            //   }
            //}

            if (empty($status)) {
                ajaxReturn('请选择苗木状态', 300);
            }
            if (empty($row) || empty($col)) {
                ajaxReturn('苗木所在行列不能为空', 300);
            }
            if (!is_numeric($row) || !is_numeric($col)) {
                ajaxReturn('请设置正确的苗木所在行列', 300);
            }
            if (strlen($row) > 3 || strlen($col) > 3) {
                ajaxReturn('苗木所在行数与列数不能超过1000', 300);
            }
            $existRowCol = $tree->where("block_id={$block_id} AND row={$row} AND col={$col} AND status=1")->count();
            if ($existRowCol) {
                ajaxReturn("该地块第{$row}行,第{$col}列已有苗木", 300);
            }

            $blockInfo = M('Block')->where("id={$block_id}")->find();

            $data = $tree->create();
            if ($data) {
                $isExec = true;
                $data['type_id'] = $small_type;
                $data['add_time'] = time();
                $data['upd_time'] = time();
                $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $row, $col);

                $tree->startTrans();
                $ret = $tree->add($data);

                if ($ret !== false) {
                    //生成苗木二维码
                    //$qrFile = createQR($ret);
                    //if ($qrFile === false) {
                    //    $isExec = false;
                    //} else {
                    //    if (aliossUploadOne($qrFile) === false) {
                    //        $isExec = false;
                    //    } else {
                    //        $updTreeQr = $tree->where("id={$ret}")->save(array('qr_local_url' => $qrFile, 'qr_remote_url' => getImgUrl($qrFile)));
                    //        if ($updTreeQr === false) {
                    //            $isExec = false;
                    //        }
                    //    }
                    //}

                    if (!empty($attr)) {
                        $insTreeAttr = array();
                        foreach ($attr as $key => $attrVal) {
                            if (!empty($attrVal)) {
                                if (is_array($attrVal)) {
                                    foreach ($attrVal as $val) {
                                        $insTreeAttr[] = array(
                                            'tree_id' => $ret,
                                            'attr_id' => $key,
                                            'attr_value' => $val,
                                        );
                                    }
                                } else {
                                    $insTreeAttr[] = array(
                                        'tree_id' => $ret,
                                        'attr_id' => $key,
                                        'attr_value' => $attrVal,
                                    );
                                }
                            }
                        }

                        if (!empty($insTreeAttr)) {
                            $ins = M('TreeAttr')->addAll($insTreeAttr);

                            if ($ins === false) {
                                $isExec = false;
                            }
                        }
                    }
                } else {
                    $isExec = false;
                }

                if ($isExec) {
                    $tree->commit();
                    ajaxReturn('添加苗木成功', 200, '', '', '', 'Admin/Tree/treeList');
                } else {
                    $tree->rollback();
                    ajaxReturn('添加苗木失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            //获取基地信息
            $base = M('Base')->field('id,name')->where('status=1')->select();

            //获取苗木分类
            $largeType = M('TreeType')->field('id,name')->where("status=1 AND pid=0")->select();

            //苗木状态
            $treeStatus = C('TREE_STATUS');

            $this->assign('base', $base);
            $this->assign('largeType', $largeType);
            $this->assign('treeStatus', $treeStatus);
            $this->display();
        }
    }

    /**
     * 批量添加苗木
     */
    public function addMoreTree() {
        if (IS_POST) {
            set_time_limit(0);
            ini_set('memory_limit', '128M');

            $base_id = I('post.base_id', 0);
            $block_id = I('post.block_id', 0);
            $large_type = I('post.large_type', 0);
            $small_type = I('post.small_type', 0);
            $attr = I('post.attr', array());
            $status = I('post.status', 0);
            $startRow = I('post.startRow', 0);
            $endRow = I('post.endRow', 0);
            $startCol = I('post.startCol', 0);
            $endCol = I('post.endCol', 0);
            $tree = M('Tree');

            if (empty($base_id)) {
                ajaxReturn('请选择所属基地', 300);
            }
            if (empty($block_id)) {
                ajaxReturn('请选择所属地块', 300);
            }
            if (empty($large_type)) {
                ajaxReturn('请选择苗木分类', 300);
            }
            if (empty($small_type)) {
                ajaxReturn('请选择苗木种类', 300);
            }

            //if (!empty($attr)) {
            //    foreach ($attr as $val) {
            //        if (empty($val)) {
            //            ajaxReturn('请设置苗木自有属性', 300);
            //        }
            //    }
            //}

            if (empty($status)) {
                ajaxReturn('请选择苗木状态', 300);
            }
            if (empty($startRow) || empty($endRow) || empty($startCol) || empty($endCol)) {
                ajaxReturn('苗木所在超始行列与终止行列不能为空', 300);
            }
            if (!is_numeric($startRow) || !is_numeric($endRow) || !is_numeric($startCol) || !is_numeric($endCol)) {
                ajaxReturn('请设置正确的苗木所在超始行列与终止行列', 300);
            }
            if (strlen($startRow) > 3 || strlen($endRow) > 3 || strlen($startCol) > 3 || strlen($endCol) > 3) {
                ajaxReturn('苗木所在超始行列与终止行列不能超过1000', 300);
            }
            if ($endRow < $startRow) {
                ajaxReturn('苗木所在终止行不能小于起始行', 300);
            }
            if ($endCol < $startCol) {
                ajaxReturn('苗木所在终止列不能小于起始列', 300);
            }
            $rowColWhere = '';
            for ($i = $startRow; $i <= $endRow; ++$i) {
                for ($j = $startCol; $j <= $endCol; ++$j) {
                    $rowColWhere .= "(row={$i} AND col={$j}) OR ";
                }
            }
            $rowColWhere = rtrim($rowColWhere, 'OR ');
            $existRowCol = $tree->where("block_id={$block_id} AND status=1 AND ({$rowColWhere})")->count();
            if ($existRowCol) {
                ajaxReturn("该地块起始行{$startRow},终止行{$endRow},起始列{$startCol},终止列{$endCol}上已有苗木", 300);
            }

            $blockInfo = M('Block')->where("id={$block_id}")->find();

            $data = $tree->create();
            if ($data) {
                //判断整个操作执行是否成功
                $isExec = true;
                $data['type_id'] = $small_type;
                $data['add_time'] = time();
                $data['upd_time'] = time();

                $tree->startTrans();
                for ($i = $startRow; $i <= $endRow; ++$i) {
                    for ($j = $startCol; $j <= $endCol; ++$j) {
                        $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $i, $j);
                        $data['row'] = $i;
                        $data['col'] = $j;

                        $ret = $tree->add($data);

                        if ($ret !== false) {
                            //生成苗木二维码
                            //$qrFile = createQR($ret);
                            //if ($qrFile === false) {
                            //    $isExec = false;
                            //} else {
                            //    if (aliossUploadOne($qrFile) === false) {
                            //        $isExec = false;
                            //    } else {
                            //        $updTreeQr = $tree->where("id={$ret}")->save(array('qr_local_url' => $qrFile, 'qr_remote_url' => getImgUrl($qrFile)));
                            //        if ($updTreeQr === false) {
                            //            $isExec = false;
                            //        }
                            //    }
                            //}

                            if (!empty($attr)) {
                                $insTreeAttr = array();
                                foreach ($attr as $key => $attrVal) {
                                    if (!empty($attrVal)) {
                                        if (is_array($attrVal)) {
                                            foreach ($attrVal as $val) {
                                                $insTreeAttr[] = array(
                                                    'tree_id' => $ret,
                                                    'attr_id' => $key,
                                                    'attr_value' => $val,
                                                );
                                            }
                                        } else {
                                            $insTreeAttr[] = array(
                                                'tree_id' => $ret,
                                                'attr_id' => $key,
                                                'attr_value' => $attrVal,
                                            );
                                        }
                                    }
                                }

                                if (!empty($insTreeAttr)) {
                                    $ins = M('TreeAttr')->addAll($insTreeAttr);

                                    if ($ins === false) {
                                        $isExec = false;
                                        break 2;
                                    }
                                }
                            }
                        } else {
                            $isExec = false;
                            break 2;
                        }
                    }
                }

                if ($isExec) {
                    $tree->commit();
                    ajaxReturn('批量添加苗木成功', 200, '', '', '', 'Admin/Tree/treeList');
                } else {
                    $tree->rollback();
                    ajaxReturn('批量添加苗木失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            //获取基地信息
            $base = M('Base')->field('id,name')->where('status=1')->select();

            //获取苗木分类
            $largeType = M('TreeType')->field('id,name')->where("status=1 AND pid=0")->select();

            //苗木状态
            $treeStatus = C('TREE_STATUS');

            $this->assign('base', $base);
            $this->assign('largeType', $largeType);
            $this->assign('treeStatus', $treeStatus);
            $this->display();
        }
    }

    /**
     * 删除苗木
     */
    public function delTree() {
        $ids = I('get.ids', '');

        if (empty($ids)) {
            ajaxReturn('请选择删除项', 300);
        }

        M()->startTrans();
        $ret = M('Tree')->where("FIND_IN_SET(id,'{$ids}')")->delete();
        $ret2 = M('TreeAttr')->where("FIND_IN_SET(tree_id,'{$ids}')")->delete();

        if ($ret !== false && $ret2 !== false) {
            M()->commit();
            ajaxReturn('删除成功', 200, '', '', '', 'Admin/Tree/treeList');
        } else {
            M()->rollback();
            ajaxReturn('删除失败', 300);
        }
    }

    /**
     * 修改苗木
     */
    public function updTree() {
        if (IS_POST) {
            $treeId = I('post.treeId', 0);
            $base_id = I('post.base_id', 0);
            $block_id = I('post.block_id', 0);
            $large_type = I('post.large_type', 0);
            $small_type = I('post.small_type', 0);
            $attr = I('post.attr', array());
            $status = I('post.status', 0);
            $row = I('post.row', 0);
            $col = I('post.col', 0);
            $tree = M('Tree');

            if (empty($treeId)) {
                ajaxReturn('苗木ID不能为空', 300);
            }
            $treeInfo = $tree->where("id={$treeId}")->find();
            if (empty($treeInfo)) {
                ajaxReturn('没有找到该苗木信息', 300);
            }
            if (empty($base_id)) {
                ajaxReturn('请选择所属基地', 300);
            }
            if (empty($block_id)) {
                ajaxReturn('请选择所属地块', 300);
            }
            if (empty($large_type)) {
                ajaxReturn('请选择苗木分类', 300);
            }
            if (empty($small_type)) {
                ajaxReturn('请选择苗木种类', 300);
            }

            if (!empty($attr)) {
                foreach ($attr as $val) {
                    if (empty($val)) {
                        ajaxReturn('请设置苗木自有属性', 300);
                    }
                }
            }

            if (empty($status)) {
                ajaxReturn('请选择苗木状态', 300);
            }
            if (empty($row) || empty($col)) {
                ajaxReturn('苗木所在行列不能为空', 300);
            }
            if (!is_numeric($row) || !is_numeric($col)) {
                ajaxReturn('请设置正确的苗木所在行列', 300);
            }
            if (strlen($row) > 3 || strlen($col) > 3) {
                ajaxReturn('苗木所在行数与列数不能超过1000', 300);
            }
            $existRowCol = $tree->where("block_id={$block_id} AND row={$row} AND col={$col} AND status=1 AND id!={$treeId}")->count();
            if ($existRowCol) {
                ajaxReturn("该地块第{$row}行,第{$col}列已有苗木", 300);
            }

            $blockInfo = M('Block')->where("id={$block_id}")->find();

            $data = $tree->create();
            if ($data) {
                $isExec = true;
                $data['type_id'] = $small_type;
                $data['upd_time'] = time();
                if ($block_id != $treeInfo['block_id']) {
                    //如果修改苗木所属地块,则重新生成编号
                    $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $row, $col);
                }
                $tree->startTrans();
                $ret = $tree->where("id={$treeId}")->save($data);

                if ($ret !== false) {
                    //删除原有苗木自有属性
                    $delTreeAttr = M('TreeAttr')->where("tree_id={$treeId}")->delete();

                    if ($delTreeAttr === false) {
                        $isExec = false;
                    } else {
                        if (!empty($attr)) {
                            //重新插入苗木自有属性
                            $insTreeAttr = array();
                            foreach ($attr as $key => $attrVal) {
                                if (!empty($attrVal)) {
                                    if (is_array($attrVal)) {
                                        foreach ($attrVal as $val) {
                                            $insTreeAttr[] = array(
                                                'tree_id' => $treeId,
                                                'attr_id' => $key,
                                                'attr_value' => $val,
                                            );
                                        }
                                    } else {
                                        $insTreeAttr[] = array(
                                            'tree_id' => $treeId,
                                            'attr_id' => $key,
                                            'attr_value' => $attrVal,
                                        );
                                    }
                                }
                            }
                            $ins = M('TreeAttr')->addAll($insTreeAttr);

                            if ($ins === false) {
                                $isExec = false;
                            }
                        }
                    }
                } else {
                    $isExec = false;
                }

                if ($isExec) {
                    $tree->commit();
                    ajaxReturn('修改苗木成功', 200);
                } else {
                    $tree->rollback();
                    ajaxReturn('修改苗木失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            $treeId = I('get.treeId', 0);

            if (empty($treeId)) {
                ajaxReturn('苗木ID不能为空', 300);
            }
            $treeInfo = M('Tree')->field('t.*,ba.id AS base_id,tt.pid AS large_type')
                    ->alias('t')
                    ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                    ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                    ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                    ->where("t.id={$treeId}")
                    ->find();

            if (empty($treeInfo)) {
                ajaxReturn('没有找到该苗木信息', 300);
            }

            //获取苗木自有属性
            $treeAttr = M('TreeAttr')->field('attr_id,attr_value,a.attr_type')
                    ->alias('ta')
                    ->join('LEFT JOIN __ATTR__ AS a ON a.id=ta.attr_id')
                    ->where("tree_id={$treeId}")
                    ->select();

            //重新构造数组,生成下标为attr_id,值为attr_value
            if (!empty($treeAttr)) {
                $tmp = array();
                foreach ($treeAttr as $item) {
                    //如果是多选属性
                    if ($item['attr_type'] == 3) {
                        $tmp[$item['attr_id']][] = $item['attr_value'];
                    } else {
                        $tmp[$item['attr_id']] = $item['attr_value'];
                    }
                }
                $treeAttr = $tmp;
            }
            $treeAttr = $this->getTreeAttr($treeInfo['type_id'], $treeAttr);

            //获取基地信息
            $base = M('Base')->field('id,name')->where('status=1')->select();

            //获取地块信息
            $block = M('Block')->field('id,sn')->where("status=1 AND base_id={$treeInfo['base_id']}")->select();

            //获取苗木分类
            $largeType = M('TreeType')->field('id,name')->where("status=1 AND pid=0")->select();

            //获取苗木种类
            $smallType = M('TreeType')->field('id,name')->where("status=1 AND pid={$treeInfo['large_type']}")->select();

            //苗木状态
            $treeStatus = C('TREE_STATUS');

            $this->assign('treeInfo', $treeInfo);
            $this->assign('treeAttr', $treeAttr);
            $this->assign('base', $base);
            $this->assign('block', $block);
            $this->assign('largeType', $largeType);
            $this->assign('smallType', $smallType);
            $this->assign('treeStatus', $treeStatus);
            $this->display();
        }
    }

    /**
     * 导出Excel
     */
    public function exportExcel() {
        set_time_limit(0);
        ini_set('memory_limit', '128M');
        $orderField = I('get.orderField', 't.id');
        $orderDirection = I('get.orderDirection', 'DESC');
        $base_id = I('get.base_id', 0);
        $block_id = I('get.block_id', 0);
        $large_type = I('get.large_type', 0);
        $small_type = I('get.small_type', 0);
        $attr = I('get.attr', array());
        $tree = M('Tree');

        //参数数组
        $params = array();
        //连表条件
        $join = '';
        //构造WHERE条件
        $where = '1=1 ';
        if (!empty($base_id)) {
            $params['base_id'] = $base_id;
            $where .= "AND ba.id={$base_id} ";
        }
        if (!empty($block_id)) {
            $params['block_id'] = $block_id;
            $where .= "AND bl.id={$block_id} ";
        }
        if (!empty($large_type)) {
            $params['large_type'] = $large_type;
            $where .= "AND tt2.id={$large_type} ";
        }
        if (!empty($small_type)) {
            $params['small_type'] = $small_type;
            $where .= "AND tt.id={$small_type} ";
        }
        if (!empty($attr)) {
            $treeAttrTable = C('DB_PREFIX') . 'tree_attr';

            foreach ($attr as $ak => $item) {
                if (!empty($item)) {
                    $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak} ON ta{$ak}.tree_id=t.id ";
                    
                    if (is_array($item)) {
                        if (array_key_exists('start', $item) && array_key_exists('end', $item)) {
                            if (!empty($item['start']) && !empty($item['end'])) {
                                $where .= "AND (ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value>={$item['start']} AND ta{$ak}.attr_value<={$item['end']}) ";
                            }
                        } else {
                            foreach ($item as $ik => $val) {
                                $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak}{$ik} ON ta{$ak}{$ik}.tree_id=t.id ";
                                $where .= "AND (ta{$ak}{$ik}.attr_id={$ak} AND ta{$ak}{$ik}.attr_value='{$val}') ";
                            }
                        }
                    } else {
                        $where .= "AND (ta{$ak}.tree_id=t.id AND ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value='{$item}') ";
                    }
                }
            }
        }

        //标题数组
        $fieldArr = array(
            'ID',
            '苗木编号',
            '苗木分类',
            '苗木种类',
            '行',
            '列',
            '自有属性',
            '状态',
            '所属地块',
            '是否挂牌',
            '添加时间',
        );

        $dataArr = array();

        $list = $tree->distinct(true)
                ->field('t.id,t.sn,tt2.name AS large_name,tt.name AS small_name,t.row,t.col,t.status,bl.sn AS block_sn,t.is_sign,t.add_time')
                ->alias('t')
                ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->join($join)
                ->where($where)
                ->order("t.id ASC,t.row ASC,t.col ASC")
                ->select();

        if (!empty($list)) {
            $treeStatus = C('TREE_STATUS');
            $isSign = C('IS_SIGN');
            foreach ($list as $item) {
                $attrInfo = '';
                $attrList = M('TreeAttr')->field('a.name,a.unit,a.attr_type,ta.attr_value')
                        ->alias('ta')
                        ->join('LEFT JOIN __ATTR__ AS a ON a.id=ta.attr_id')
                        ->where("ta.tree_id={$item['id']}")
                        ->select();

                if (!empty($attrList)) {
                    foreach ($attrList as $attrItem) {
                        //自有属性类型为文本的带单位
                        if ($attrItem['attr_type'] == 1) {
                            $attrInfo .= "{$attrItem['name']} : {$attrItem['attr_value']} {$attrItem['unit']} \r\n";
                        } else {
                            $attrInfo .= "{$attrItem['name']} : {$attrItem['attr_value']} \r\n";
                        }
                    }
                }

                $dataArr[] = array(
                    $item['id'],
                    $item['sn'],
                    $item['large_name'],
                    $item['small_name'],
                    $item['row'],
                    $item['col'],
                    $attrInfo,
                    array_key_exists($item['status'], $treeStatus) ? $treeStatus[$item['status']] : '',
                    $item['block_sn'],
                    array_key_exists($item['is_sign'], $isSign) ? $isSign[$item['is_sign']] : '',
                    $item['add_time'] ? date('Y-m-d H:i:s', intval($item['add_time'])) : '',
                );
            }
        }

        exportExcel($fieldArr, $dataArr);
    }

    /**
     * 导出打印Excel
     */
    public function exportPrintExcel() {
        set_time_limit(0);
        ini_set('memory_limit', '128M');
        $orderField = I('get.orderField', 't.id');
        $orderDirection = I('get.orderDirection', 'DESC');
        $base_id = I('get.base_id', 0);
        $block_id = I('get.block_id', 0);
        $large_type = I('get.large_type', 0);
        $small_type = I('get.small_type', 0);
        $attr = I('get.attr', array());
        $tree = M('Tree');

        //参数数组
        $params = array();
        //连表条件
        $join = '';
        //构造WHERE条件,
        $where = '1=1 AND t.is_sign=0 ';
        if (!empty($base_id)) {
            $params['base_id'] = $base_id;
            $where .= "AND ba.id={$base_id} ";
        }
        if (!empty($block_id)) {
            $params['block_id'] = $block_id;
            $where .= "AND bl.id={$block_id} ";
        }
        if (!empty($large_type)) {
            $params['large_type'] = $large_type;
            $where .= "AND tt2.id={$large_type} ";
        }
        if (!empty($small_type)) {
            $params['small_type'] = $small_type;
            $where .= "AND tt.id={$small_type} ";
        }
        if (!empty($attr)) {
            $treeAttrTable = C('DB_PREFIX') . 'tree_attr';

            foreach ($attr as $ak => $item) {
                if (!empty($item)) {
                    $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak} ON ta{$ak}.tree_id=t.id ";
                    
                    if (is_array($item)) {
                        if (array_key_exists('start', $item) && array_key_exists('end', $item)) {
                            if (!empty($item['start']) && !empty($item['end'])) {
                                $where .= "AND (ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value>={$item['start']} AND ta{$ak}.attr_value<={$item['end']}) ";
                            }
                        } else {
                            foreach ($item as $ik => $val) {
                                $join .= "LEFT JOIN {$treeAttrTable} AS ta{$ak}{$ik} ON ta{$ak}{$ik}.tree_id=t.id ";
                                $where .= "AND (ta{$ak}{$ik}.attr_id={$ak} AND ta{$ak}{$ik}.attr_value='{$val}') ";
                            }
                        }
                    } else {
                        $where .= "AND (ta{$ak}.tree_id=t.id AND ta{$ak}.attr_id={$ak} AND ta{$ak}.attr_value='{$item}') ";
                    }
                }
            }
        }

        //标题数组
        $fieldArr = array(
            'ID',
            '苗木编号',
            '苗木分类',
            '行列',
        );

        $dataArr = array();

        $list = $tree->distinct(true)
                ->field('t.id,t.sn,tt2.name AS large_name,tt.name AS small_name,t.row,t.col,t.status,bl.sn AS block_sn,t.is_sign,t.add_time')
                ->alias('t')
                ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->join($join)
                ->where($where)
                ->order("t.id ASC,t.row ASC,t.col ASC")
                ->select();

        if (!empty($list)) {
            $treeStatus = C('TREE_STATUS');
            $isSign = C('IS_SIGN');
            $idArr = array();

            foreach ($list as $item) {
                $idArr[] = $item['id'];

                $attrInfo = '';
                $attrList = M('TreeAttr')->field('a.name,a.unit,a.attr_type,ta.attr_value')
                        ->alias('ta')
                        ->join('LEFT JOIN __ATTR__ AS a ON a.id=ta.attr_id')
                        ->where("ta.tree_id={$item['id']}")
                        ->select();

                if (!empty($attrList)) {
                    foreach ($attrList as $attrItem) {
                        //自有属性类型为文本的带单位
                        if ($attrItem['attr_type'] == 1) {
                            $attrInfo .= "{$attrItem['name']} : {$attrItem['attr_value']} {$attrItem['unit']} \r\n";
                        } else {
                            $attrInfo .= "{$attrItem['name']} : {$attrItem['attr_value']} \r\n";
                        }
                    }
                }

                $dataArr[] = array(
                    $item['id'],
                    $item['sn'],
                    $item['large_name'] . ':' . $item['small_name'],
                    $item['row'] . '行' . $item['col'] . '列',
                );
            }

            $ids = implode(',', $idArr);
            M('Tree')->where("FIND_IN_SET(id,'{$ids}')")->save(array('is_sign' => 1));
        }

        header('Set-Cookie: fileDownload=true; path=/');
        exportExcel($fieldArr, $dataArr);
    }

    /**
     * 导入Excel
     */
    public function importExcel() {
        if (IS_POST) {
            set_time_limit(0);
            ini_set('memory_limit', '256M');

            $info = uploadOne($_FILES['file'], array('savePath' => 'import/', 'exts' => array('xls', 'xlsx'), 'maxSize' => 8388608));
            if (!$info) {
                ajaxReturn('上传失败', 300);
            } else {
                vendor('PHPExcel.PHPExcel');

                $filePath = C('UPLOAD_CONFIG.rootPath') . $info['savepath'] . $info['savename'];

                $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
                $cacheSettings = array();
                \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
                $reader = new \PHPExcel_Reader_Excel5();
                $excel = $reader->load($filePath);
                $data = $excel->getActiveSheet()->toArray();

                if (empty($data) || count($data) == 1) {
                    ajaxReturn('数据不能为空', 300);
                }
                unset($data[0]);

                //获取苗木分类种类信息
                $treeType = M('TreeType')->field('id,name')->where('status=1')->select();
                if (!empty($treeType)) {
                    $tmp = array();
                    foreach ($treeType as $item) {
                        $tmp[$item['id']] = $item['name'];
                    }
                    $treeType = array_flip($tmp);
                }
                //苗木状态信息
                $treeStatus = array_flip(C('TREE_STATUS'));
                //苗木是否挂牌
                $treeIsSign = array_flip(C('IS_SIGN'));
                //获取基地信息
                $baseInfo = M('Base')->field('id,name')->where('status=1')->select();
                if (!empty($baseInfo)) {
                    $tmp = array();
                    foreach ($baseInfo as $item) {
                        $tmp[$item['id']] = $item['name'];
                    }
                    $baseInfo = array_flip($tmp);
                }
                //获取地块信息
                $blockInfo = M('Block')->field('id,sn')->where('status=1')->select();
                if (!empty($blockInfo)) {
                    $tmp = array();
                    foreach ($blockInfo as $item) {
                        $tmp[$item['id']] = $item['sn'];
                    }
                    $blockInfo = array_flip($tmp);
                }

                $errorInfo = array();
                foreach ($data as $num => $item) {
                    $num = $num + 1;

                    if (count($item) != 9) {
                        ajaxReturn('数据列数不正确', 300);
                    }

                    $large_name = $item[0];
                    $small_name = $item[1];
                    $row = $item[2];
                    $col = $item[3];
                    $status = $item[4];
                    $base_name = $item[5];
                    $block_sn = $item[6];
                    $is_sign_name = $item[7];

                    if (!array_key_exists($large_name, $treeType)) {
                        $errorInfo[] = "第{$num}行,苗木分类不存在";
                        continue;
                    }
                    if (!array_key_exists($small_name, $treeType)) {
                        $errorInfo[] = "第{$num}行,苗木种类不存在";
                        continue;
                    }
                    if ($row <= 0 || $row > 999 || $col <= 0 || $col > 999) {
                        $errorInfo[] = "第{$num}行,苗木行与列不正确";
                        continue;
                    }
                    if (!array_key_exists($status, $treeStatus)) {
                        $errorInfo[] = "第{$num}行,苗木状态不正确";
                        continue;
                    }
                    if (!array_key_exists($base_name, $baseInfo)) {
                        $errorInfo[] = "第{$num}行,苗木所属基地不存在";
                        continue;
                    }
                    if (!array_key_exists($block_sn, $blockInfo)) {
                        $errorInfo[] = "第{$num}行,苗木所属地块不存在";
                        continue;
                    }
                    if (!array_key_exists($is_sign_name, $treeIsSign)) {
                        $errorInfo[] = "第{$num}行,苗木是否挂牌不正确";
                        continue;
                    }

                    $large_type = $treeType[$large_name];
                    $small_type = $treeType[$small_name];
                    $status = $treeStatus[$status];
                    $base_id = $baseInfo[$base_name];
                    $block_id = $blockInfo[$block_sn];
                    $is_sign = $treeIsSign[$is_sign_name];

                    $existRowCol = M('Tree')->where("block_id={$block_id} AND row={$row} AND col={$col} AND status=1")->count();
                    if ($existRowCol) {
                        $errorInfo[] = "第{$num}行,该地块第{$row}行,第{$col}列已有苗木";
                        continue;
                    }

                    $ret = M('Tree')->add(array(
                        'block_id' => $block_id,
                        'sn' => $block_sn . sprintf("%03d%03d", $row, $col),
                        'type_id' => $small_type,
                        'row' => $row,
                        'col' => $col,
                        'status' => $status,
                        'is_sign' => $is_sign,
                        'add_time' => time(),
                        'upd_time' => time(),
                    ));

                    if (!$ret) {
                        $errorInfo[] = "第{$num}行,导入失败";
                    }
                }

                if (empty($errorInfo)) {
                    ajaxReturn('数据全部导入成功', 200, '', '', '', 'Admin/Tree/treeList');
                } else {
                    ajaxReturn('数据全部导入失败', 300, $errorInfo);
                }
            }
        } else {

            $this->display();
        }
    }

    /**
     * 标签打印
     */
    public function labelPrint() {
        
    }

    /**
     * 导入模板下载
     */
    public function importTemplate() {
        $filePath = './Down';
        $fileName = 'teplates.xls';
        $file = $filePath . '/' . $fileName;
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $fileName);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }

    /**
     * 获取苗木自有属性
     */
    public function getTreeAttr($typeId, $treeAttr = array(), $isSearch = false) {
        if (empty($typeId)) {
            return '';
        }

        //获取种类的自有属性
        $attrList = M('Attr')->field('id,attr_type,name,value,unit')
                ->where("status=1 AND type_id={$typeId}")
                ->order('sort ASC')
                ->select();

        if (empty($attrList)) {
            return '';
        }

        $attrStr = '';
        foreach ($attrList as $item) {
            switch ($item['attr_type']) {
                case "1" :
                    //如果是文本
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    if (array_key_exists($item['id'], $treeAttr)) {
                        if ($isSearch) {
                            $start = !empty($treeAttr[$item['id']]['start']) ? $treeAttr[$item['id']]['start'] : '';
                            $end = !empty($treeAttr[$item['id']]['end']) ? $treeAttr[$item['id']]['end'] : '';
                            $attrStr .= "<input type='text' name='attr[{$item['id']}][start]' value='{$start}' class='form-control' style='width:100px'>";
                            $attrStr .= '到';
                            $attrStr .= "<input type='text' name='attr[{$item['id']}][end]' value='{$end}' class='form-control' style='width:100px'>{$item['unit']}";
                        } else {
                            $attrStr .= "<input type='text' name='attr[{$item['id']}]' value='{$treeAttr[$item['id']]}' class='form-control' style='width:150px'>{$item['unit']}";
                        }
                    } else {
                        if ($isSearch) {
                            $attrStr .= "<input type='text' name='attr[{$item['id']}]' class='form-control' style='width:100px'>";
                            $attrStr .= '到';
                            $attrStr .= "<input type='text' name='attr[{$item['id']}]' class='form-control' style='width:100px'>{$item['unit']}";
                        } else {
                            $attrStr .= "<input type='text' name='attr[{$item['id']}]' class='form-control' style='width:150px'>{$item['unit']}";
                        }
                    }
                    $attrStr .= "</div>";
                    break;
                case "2":
                    //如果是单选
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    foreach ($valueArr as $val) {
                        $checked = '';
                        if (array_key_exists($item['id'], $treeAttr) && ($treeAttr[$item['id']] == $val)) {
                            $checked = "checked='checked'";
                        }
                        $attrStr .= "&nbsp;&nbsp;<input type='radio' name='attr[{$item['id']}]' value='{$val}' class='form-control' {$checked}>{$val}";
                    }
                    $attrStr .= "</div>";
                    break;
                case "3":
                    //如果是多选
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    foreach ($valueArr as $val) {
                        $checked = '';
                        if (array_key_exists($item['id'], $treeAttr) && is_array($treeAttr[$item['id']])) {
                            foreach ($treeAttr[$item['id']] as $attrVal) {
                                if ($val == $attrVal) {
                                    $checked = "checked='checked'";
                                    break;
                                }
                            }
                        }
                        $attrStr .= "&nbsp;&nbsp;<input type='checkbox' name='attr[{$item['id']}][]' value='{$val}' class='form-control' {$checked}>{$val}";
                    }
                    $attrStr .= "</div>";
                    break;
                case "4":
                    //如果是下拉框
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    $attrStr .= "<select name='attr[{$item['id']}]' class='form-control' style='width:150px'><option value='0'>请选择</option>";
                    foreach ($valueArr as $val) {
                        $selected = '';
                        if (array_key_exists($item['id'], $treeAttr) && $treeAttr[$item['id']] == $val) {
                            $selected = "selected='selected'";
                        }
                        $attrStr .= "<option value='{$val}' {$selected}>{$val}</option>";
                    }
                    $attrStr .= "</select></div>";
                    break;
                default:
                    break;
            }
        }
        return $attrStr;
    }

    /**
     * 获取苗木种类自有属性
     */
    public function getTreeTypeAttr() {
        $typeId = I('post.typeId', 0);
        $isSearch = I('post.isSearch', 0);

        if (empty($typeId)) {
            ajaxReturn('', 300, array());
        }

        //获取种类的自有属性
        $attrList = M('Attr')->field('id,attr_type,name,value,unit')
                ->where("status=1 AND type_id={$typeId}")
                ->order('sort ASC')
                ->select();

        if (empty($attrList)) {
            ajaxReturn('', 300, array());
        }

        $attrStr = '';
        foreach ($attrList as $item) {
            switch ($item['attr_type']) {
                case "1" :
                    //如果是文本
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    if ($isSearch) {
                        $attrStr .= "<input type='text' name='attr[{$item['id']}][start]' class='form-control' style='width:100px'>";
                        $attrStr .= '到';
                        $attrStr .= "<input type='text' name='attr[{$item['id']}][end]' class='form-control' style='width:100px'>{$item['unit']}";
                    } else {
                        $attrStr .= "<input type='text' name='attr[{$item['id']}]' class='form-control' style='width:150px'>{$item['unit']}";
                    }
                    $attrStr .= "</div>";
                    break;
                case "2":
                    //如果是单选
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    foreach ($valueArr as $val) {
                        $attrStr .= "&nbsp;&nbsp;<input type='radio' name='attr[{$item['id']}]' value='{$val}' class='form-control'>{$val}";
                    }
                    $attrStr .= "</div>";
                    break;
                case "3":
                    //如果是多选
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    foreach ($valueArr as $val) {
                        $attrStr .= "&nbsp;&nbsp;<input type='checkbox' name='attr[{$item['id']}][]' value='{$val}' class='form-control'>{$val}";
                    }
                    $attrStr .= "</div>";
                    break;
                case "4":
                    //如果是下拉框
                    $valueArr = explode(',', $item['value']);
                    $attrStr .= "<div class='attrRow'>";
                    $attrStr .= "<label>{$item['name']}:</label>";
                    $attrStr .= "<select name='attr[{$item['id']}]' class='form-control' style='width:150px'><option value='0'>请选择</option>";
                    foreach ($valueArr as $val) {
                        $attrStr .= "<option value='{$val}'>{$val}</option>";
                    }
                    $attrStr .= "</select></div>";
                    break;
                default:
                    break;
            }
        }
        ajaxReturn('', 200, array('attrStr' => $attrStr));
    }

    /**
     * 获取苗木分类种类信息
     */
    public function getTreeTypeInfo() {
        $treeTypeInfo = array();
        $treeTypeRet = M('Tree')->group('type_id')->getField('type_id', true);
        $treeTypeIds = implode(',', $treeTypeRet);
        $treeTypeList = M('TreeType')->field('tt.id,tt.name AS small_name,tt2.name AS large_name')
                ->alias('tt')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->where("FIND_IN_SET(tt.id,'{$treeTypeIds}')")
                ->select();

        if (!empty($treeTypeList)) {
            $tmp = array();
            foreach ($treeTypeList as $item) {
                $tmp[$item['id']] = array(
                    'large_name' => $item['large_name'],
                    'small_name' => $item['small_name'],
                );
            }
            $treeTypeInfo = $tmp;
        }
        return $treeTypeInfo;
    }

    /**
     * 批量设置苗木状态
     */
    public function batchSetTreeStatus() {
        if (IS_POST) {
            $ids = I('post.ids', '');
            $status = I('post.status', 0);

            if (empty($ids)) {
                ajaxReturn('苗木ID不能为空', 300);
            }
            if (empty($status)) {
                ajaxReturn('苗木状态不能为空', 300);
            }

            $ret = M('Tree')->where("FIND_IN_SET(id,'{$ids}')")->save(array('status' => $status));

            if ($ret !== false) {
                ajaxReturn('批量设置状态成功', 200, '', '', '', 'Admin/Tree/treeList', '', true);
            } else {
                ajaxReturn('批量设置状态失败', 300);
            }
        } else {
            $ids = I('get.ids', '');
            $ids = trim($ids, ',');

            if (empty($ids)) {
                ajaxReturn('请选择苗木', 300);
            }

            //苗木状态
            $treeStatus = C('TREE_STATUS');

            $this->assign('ids', $ids);
            $this->assign('treeStatus', $treeStatus);
            $this->display();
        }
    }

}
